from flask_restful import fields, Resource, reqparse, abort, marshal

from main.apis.admin import parser_base
from main.apis.api_constant import SUPER_ADMINS, HTTP_CREATE_OK, HTTP_OK
from main.apis.utils import get_admin_user, permission_required, generate_admin_token
from main.ext import cache
from main.models.admin.admin_model import AdminModel, PERMISSION_SU

admin_fields = {
    'username': fields.String,
    'password': fields.String(attribute='_password')  # 不指定attribute会访问password，触发异常
}

single_admin_fields = {
    'data': fields.Nested(admin_fields),
    'status': fields.Integer,
    'msg': fields.String
}

# parser_base = reqparse.RequestParser()
# # 根据三个参数的优先级来排序，最先判断的应该是请求参数，然后是用户名，最后是密码
# # parser_base.add_argument('action', type=str, required=True, help='请输入请求参数')
# parser_base.add_argument('username', type=str, required=True, help='请输入用户名')
# parser_base.add_argument('password', type=str, required=True, help='请输入密码')
# parser_base.add_argument('permission', type=int, help='请输入权限')
parser = parser_base.copy()
parser.remove_argument('action')


class AdminRegisterResource(Resource):
    # admin账号的注册应该只有管理员才能操作，登录不需要，所以注册和登录应该写到两个不同的class的post中写成两个api
    # 但这种写法必须在数据库中内置一个超级管理员账户才可以进行正常的注册登录，创建第一个超级管理员账户应该先注释下面的装饰器
    @permission_required(PERMISSION_SU)
    def post(self):
        args = parser.parse_args()
        username = args.get('username')
        password = args.get('password')
        permission = args.get('permission')
        print(permission)

        user = AdminModel.query.filter(AdminModel.username == username).first()
        if user:
            abort(403, error='用户已存在！')
        admin = AdminModel()
        admin.username = username
        admin.password = password
        if permission:
            admin.permission = permission
        if username in SUPER_ADMINS:
            admin.is_super = True
            admin.permission = PERMISSION_SU
        if not admin.save():
            abort(400, msg='创建失败')
        data = {
            'status': HTTP_CREATE_OK,
            'msg': '用户创建成功',
            'data': admin
        }
        return marshal(data, single_admin_fields)


class AdminLoginResource(Resource):
    def post(self):
        args = parser.parse_args()
        username = args.get('username')
        password = args.get('password')

        # 判断用户是否存在
        user = get_admin_user(username)
        if not user:
            abort(403, error='用户不存在')
        # 检查用户是否被删除
        if user.is_delete:
            abort(403, error='此用户已被删除')
        # 验证密码
        if not user.check_password(password):
            abort(403, error='用户名和密码不匹配')
        token = generate_admin_token()
        cache.set(token, user.id, timeout=60 * 60)
        data = {
            'status': HTTP_OK,
            'msg': '已登陆',
            'token': token
        }
        return data
